import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import 'package:markdown/markdown.dart' as markdown;
import 'package:video_player/video_player.dart' as vp;
import '../widgets/audio_record_view.dart';

import '../common/constants.dart';
import '../common/images.dart';
import '../common/routes.dart';
import '../common/utils.dart';
import '../controllers/chat_controller.dart';
import '../model/chat_message.dart';
import '../model/common_mode.dart';
import '../utils/utils.dart';
import '../widgets/audio_message_view.dart';
import '../widgets/typing_indicator.dart';

class ChatPage2 extends StatelessWidget {
  ChatPage2({super.key});

  final controller = Get.find<ChatController>(tag: Get.arguments['pipeId']);

  _buildCoverView() {
    if (controller.bgType.value == "video" && controller.videoInitialized.value) {
      return Stack(
        children: [
          Container(
            color: Colors.black,
            width: double.infinity,
            height: double.infinity,
          ),
          Center(
            child: SizedBox.expand(
              child: FittedBox(
                fit: BoxFit.cover,
                child: SizedBox(
                  width: controller.videoPlayerController?.value.size.width,
                  height: controller.videoPlayerController?.value.size.height,
                  child: vp.VideoPlayer(controller.videoPlayerController!),
                ),
              ),
            ),
          )
        ],
      );
    } else if (controller.bgType.value == "img") {
      return Stack(
        children: [
          Container(
            color: Colors.black,
            width: double.infinity,
            height: double.infinity,
          ),
          SizedBox(
            width: double.infinity,
            height: double.infinity,
            child: TweenAnimationBuilder<double>(
                tween: Tween<double>(begin: 0.0, end: 1.0),
                curve: Curves.ease,
                duration: const Duration(seconds: 1),
                builder: (BuildContext context, double opacity, Widget? child) {
                  return Opacity(
                    opacity: opacity,
                    child: CachedNetworkImage(imageUrl: controller.bgSrcUrl.value, fit: BoxFit.cover),
                  );
                }),
          )
        ],
      );
    }
    return Container(color: Colors.black);
  }

  _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: Colors.transparent,
      automaticallyImplyLeading: false,
      iconTheme: const IconThemeData(
        color: Colors.white,
      ),
      flexibleSpace: FlexibleSpaceBar(
        background: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: <Color>[
                Colors.black,
                Colors.transparent,
              ],
            ),
          ),
        ),
      ),
      title: Row(children: [
        GestureDetector(
            child: Container(
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black38,
              ),
              padding: const EdgeInsets.all(5.0),
              child: const Icon(Icons.arrow_back_ios_new, size: 20),
            ),
            onTap: () {
              FocusScope.of(context).unfocus();
              Get.back();
            }),
        const SizedBox(width: 10),
        //Expanded(child: Text(_pipeSceneModel?.pipe.cartoon?.name ?? "", style: const TextStyle(color: Colors.red, fontSize: 16, fontWeight: FontWeight.w500))),
        GestureDetector(
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
            decoration: BoxDecoration(color: Colors.black54, borderRadius: BorderRadius.circular(16)),
            child: Row(children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: CachedNetworkImage(
                  height: 24,
                  width: 24,
                  fadeInDuration: const Duration(seconds: 0),
                  fadeOutDuration: const Duration(seconds: 0),
                  fit: BoxFit.cover,
                  imageUrl: controller.pipeSceneModel?.pipe.cartoon?.avatar ?? "",
                  errorWidget: (_, url, object) {
                    return Container(color: Colors.grey[200]);
                  },
                ),
              ),
              const SizedBox(width: 4),
              Text(
                controller.pipeSceneModel?.pipe.cartoon?.name ?? "",
                style: const TextStyle(color: Colors.white, fontSize: 14),
              ),
              const SizedBox(width: 6),
              GestureDetector(
                  child: Container(
                    width: 30,
                    decoration: BoxDecoration(
                      color: Constants.themeColor,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: const Icon(Icons.add, size: 20),
                  ),
                  onTap: () {
                    print("关注-------");
                  })
            ]),
          ),
          onTap: () {
            var cartoonId = controller.pipeSceneModel?.pipe.cartoon?.id ?? "";
            if (cartoonId.isNotEmpty) {
              Get.toNamed(Routes.CARTOON_INFO, arguments: {"cartoonId": cartoonId});
            }
          },
        ),
        const Spacer(),
        GestureDetector(
            child: Container(
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black38,
              ),
              padding: const EdgeInsets.all(5.0),
              child: Icon(controller.isMute.value ? Icons.volume_off : Icons.volume_up, size: 20),
            ),
            onTap: () async {
              await controller.onToggleMute();
            }),
        const SizedBox(width: 5),
        GestureDetector(
            child: Container(
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black38,
              ),
              padding: const EdgeInsets.all(5.0),
              child: const Icon(Icons.more_horiz, size: 20),
            ),
            onTap: () {
              _showBottomSheet(context);
            })
      ]),
    );
  }

  Widget _buildShortcutItem(BuildContext context, int index) {
    final message = controller.shortbtns[index];
    //btn-border、btn-default、btn-fill
    Color borderColor = Color(0xFF6AE066);
    Color textColor = Color(0xFF6AE066);
    Color backgroundColor = Colors.black;
    final style = message.sub.where((x) => x.type == "str" && x.inName == "style").firstOrNull?.val ?? '';
    if (style == 'btn-default') {
      borderColor = Colors.black;
      textColor = Colors.white;
      backgroundColor = Colors.white12;
    } else if (style == 'btn-fill') {
      borderColor = Colors.black;
      textColor = Colors.black;
      backgroundColor = Color(0xFF6AE066);
    }
    return InkWell(
      onTap: () {
        if (message.inName == "btnAd") {
          final shortcutItem = message.sub.where((x) => x.inName == "adEnded").firstOrNull;
          if (shortcutItem != null) {
            Fluttertoast.showToast(msg: shortcutItem.val ?? '', gravity: ToastGravity.CENTER, backgroundColor: Colors.white, textColor: Constants.themeColor);
          }
        }
        controller.sendShortcutMessage(message);
      },
      child: Container(
        margin: EdgeInsets.only(left: 10, top: 2, bottom: 2),
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: BorderRadius.circular(25),
          border: Border.all(color: borderColor, width: 1),
        ),
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 0),
        child: Center(
          child: Row(
            children: [
              if (message.inName == "btnAd")
                Padding(
                  padding: EdgeInsets.only(right: 5),
                  child: Icon(
                    Icons.smart_display,
                    size: 20,
                    color: textColor,
                  ),
                ),
              Text(
                message.val,
                style: TextStyle(color: textColor),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMorePanel() {
    return Container(
      padding: EdgeInsets.all(15),
      child: Row(
        children: [
          _buildMenuItem("icon_reset.png", "重启对话", () {
            controller.clearChat();
          }),
          _buildMenuItem("icon_share.png", "分享", () {
            _showBottomSheet(Get.context!);
          }),
          _buildMenuItem("icon_report.png", "举报", () {
            Get.toNamed(Routes.REPORT);
          })
        ],
      ),
    );
  }

  _buildMenuItem(String imageName, String title, VoidCallback onTap) {
    return GestureDetector(
      onTap: () {
        onTap();
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 12),
        child: Column(
          children: [
            Image.asset(
              "assets/images/$imageName",
              width: 50,
              height: 50,
              fit: BoxFit.cover,
            ),
            SizedBox(
              height: 5,
            ),
            Text(
              title,
              style: TextStyle(color: Colors.grey, fontSize: 12),
            )
          ],
        ),
      ),
    );
  }

  _buildInputImage() {
    if (controller.isUploadImage.value) {
      return Stack(clipBehavior: Clip.none, alignment: Alignment.centerLeft, children: [
        Container(
          width: 60,
          height: 60,
          padding: EdgeInsets.all(15),
          decoration: BoxDecoration(
            color: Colors.black54,
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: const CircularProgressIndicator(
            strokeWidth: 1,
            color: Colors.white,
          ),
        )
      ]);
    } else {
      return Stack(
        clipBehavior: Clip.none,
        alignment: Alignment.centerLeft,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: Image.file(
              File(controller.selectedImagePath.value),
              width: 60,
              height: 60,
              fit: BoxFit.cover,
            ),
          ),
          Positioned(
            top: -6,
            left: 50,
            child: InkWell(
              child: Container(
                width: 20,
                height: 20,
                decoration: BoxDecoration(
                  color: Colors.black45,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Icon(
                  Icons.close,
                  size: 15,
                  color: Colors.white60,
                ),
              ),
              onTap: () {
                controller.selectedImagePath.value = '';
                controller.selectedImageUrl.value = '';
                controller.showSendButton.value = false;
              },
            ),
          ),
        ],
      );
    }
  }

  _buildTextInput() {
    if (controller.inputType.value == "str") {
      return Expanded(
        child: TextField(
          controller: controller.textController,
          focusNode: controller.focusNode,
          keyboardType: TextInputType.multiline,
          style: TextStyle(color: Colors.white, fontSize: 15),
          cursorColor: Colors.white,
          maxLines: 5,
          minLines: 1,
          decoration: InputDecoration(
            isDense: true,
            hintText: '发消息',
            hintStyle: TextStyle(color: Colors.white54, fontSize: 15),
            filled: true,
            fillColor: Colors.transparent,
            contentPadding: EdgeInsets.symmetric(horizontal: 0, vertical: 12),
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ),
          onSubmitted: (value) => controller.sendTextMessage(),
        ),
      );
    } else if (controller.inputType.value == "img") {
      return Expanded(
        child: InkWell(
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 2),
            child: controller.selectedImagePath.value.isNotEmpty
                ? Padding(
                    padding: EdgeInsets.all(10),
                    child: _buildInputImage(),
                  )
                : Container(
                    padding: EdgeInsets.only(left: 10),
                    height: 44,
                    child: Row(
                      children: [
                        Image.asset(
                          "assets/images/icon_img_add.png",
                          width: 22,
                          height: 22,
                          fit: BoxFit.cover,
                        ),
                        SizedBox(
                          width: 8,
                        ),
                        Text(
                          '上传图片',
                          style: TextStyle(color: Colors.white54),
                        )
                      ],
                    ),
                  ),
          ),
          onTap: () {
            controller.pickImage();
          },
        ),
      );
    } else if (controller.inputType.value == "mixed") {
      final placeholder = controller.pipeSceneModel?.pipe.inParams?.firstWhereOrNull((x) => x.name == "k_1")?.placeholder ?? "发消息";
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 15),
          margin: EdgeInsets.only(left: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              controller.selectedImagePath.value.isNotEmpty
                  ? Padding(
                      padding: EdgeInsets.symmetric(vertical: 2),
                      child: _buildInputImage(),
                    )
                  : GestureDetector(
                      child: Row(
                        children: [
                          Image.asset(
                            "assets/images/icon_img_add.png",
                            width: 22,
                            height: 22,
                            fit: BoxFit.cover,
                          ),
                          SizedBox(
                            width: 8,
                          ),
                          Text(
                            '上传图片',
                            style: TextStyle(color: Colors.white54, fontSize: 15),
                          )
                        ],
                      ),
                      onTap: () {
                        controller.pickImage();
                      },
                    ),
              SizedBox(
                height: 8,
              ),
              Divider(
                color: Colors.white.withAlpha(8),
                height: 1,
              ),
              SizedBox(
                height: 8,
              ),
              TextField(
                controller: controller.textController,
                focusNode: controller.focusNode,
                keyboardType: TextInputType.multiline,
                style: TextStyle(color: Colors.white, fontSize: 15),
                cursorColor: Colors.white,
                maxLines: 5,
                minLines: 1,
                decoration: InputDecoration(
                  isDense: true,
                  hintText: placeholder,
                  hintStyle: TextStyle(color: Colors.white54, fontSize: 15),
                  contentPadding: EdgeInsets.zero,
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                  ),
                ),
              )
            ],
          ),
        ),
      );
    } else {
      return SizedBox.shrink();
    }
  }

  _buildInputBar(BuildContext context) {
    final bottomPadding = MediaQuery.of(context).padding.bottom;
    return Container(
      padding: EdgeInsets.only(left: 0, top: 10, right: 0, bottom: bottomPadding + 10),
      color: Colors.black,
      child: Column(
        children: [
          if (controller.shortbtns.isNotEmpty)
            Container(
              height: 40,
              margin: EdgeInsets.only(bottom: 10),
              child: ListView.builder(scrollDirection: Axis.horizontal, itemCount: controller.shortbtns.length, itemBuilder: _buildShortcutItem),
            ),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 10),
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Colors.white12),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                if (controller.inputType.value != "mixed")
                  if (controller.isCustomReply.value)
                    Padding(
                      padding: const EdgeInsets.only(left: 5),
                      child: IconButton(
                        onPressed: () {
                          controller.isCustomReply.value = false;
                          controller.disabledInput.value = true;
                        },
                        style: IconButton.styleFrom(
                          backgroundColor: Colors.white.withAlpha(50),
                          side: BorderSide(
                            width: 1,
                            color: Colors.white.withAlpha(12),
                          ),
                        ),
                        icon: const Icon(
                          CupertinoIcons.left_chevron,
                          color: Colors.white,
                          size: 24,
                        ),
                      ),
                    ),
                if (controller.inputType.value == "str")
                  IconButton(
                    onPressed: () async {
                      await controller.requestMicrophonePermission();
                    },
                    icon: const Icon(
                      Icons.mic,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                _buildTextInput(),
                controller.showSendButton.value
                    ? IconButton(
                        onPressed: () {
                          FocusScope.of(context).requestFocus(FocusNode());
                          controller.sendAction();
                        },
                        style: IconButton.styleFrom(
                          backgroundColor: Constants.themeColor,
                        ),
                        padding: EdgeInsets.all(0),
                        icon: Icon(
                          Icons.arrow_upward,
                          color: Colors.white,
                          size: 24,
                        ),
                      )
                    : IconButton(
                        onPressed: () {
                          FocusScope.of(context).requestFocus(FocusNode());
                          controller.isPanelVisible.value = !controller.isPanelVisible.value;
                        },
                        icon: Container(
                          padding: EdgeInsets.all(3),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(color: Colors.white, width: 1),
                          ),
                          child: Icon(
                            controller.isPanelVisible.value ? Icons.close : CupertinoIcons.add,
                            color: Colors.white,
                            size: 22,
                          ),
                        ),
                      ),
              ],
            ),
          ),
          AnimatedCrossFade(
            sizeCurve: Curves.easeInOut,
            firstChild: SizedBox.shrink(),
            secondChild: _buildMorePanel(),
            crossFadeState: controller.isPanelVisible.value ? CrossFadeState.showSecond : CrossFadeState.showFirst,
            duration: Duration(milliseconds: 250),
          ),
        ],
      ),
    );
  }

  List<Widget> _buildQuickInputSheetView() {
    return controller.quickInputSheetButtonList.map(
      (data) {
        bool isCustomReply = data.customProperties?.keys.contains("noInput") ?? false;
        return GestureDetector(
          child: Container(
            width: double.infinity,
            decoration: BoxDecoration(
              color: isCustomReply ? Colors.white24 : Color(0xFF6AE066),
              borderRadius: BorderRadius.circular(10),
            ),
            margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
            padding: EdgeInsets.all(10),
            child: Center(
              child: Text(
                data.title,
                style: TextStyle(color: isCustomReply ? Colors.white : Color(0xFF050805), fontSize: 15),
              ),
            ),
          ),
          onTap: () {
            if (isCustomReply) {
              controller.disabledInput.value = false;
              controller.isCustomReply.value = true;
            } else {
              controller.sendQuickReply(data);
            }
          },
        );
      },
    ).toList();
  }

  bool _isMarkdown(String text) {
    final markdownPattern = RegExp(
      r'(^#{1,6}\s+.*$|' // 标题
      r'(\*\*|__)(.*?)\1|' // 加粗
      r'(\*|_)(.*?)\1|' // 斜体
      r'$begin:math:display$.*?$end:math:display$$begin:math:text$.*?$end:math:text$|' // 链接
      r'^>.*$|' // 引用
      r'```.*?```|`.*?`)', // 代码块
      multiLine: true,
    );
    return markdownPattern.hasMatch(text);
  }

  _buildSystemMessageWidget(dynamic data) {
    if (data is List<MessageItemModel>) {
      final messageList = data;
      List<Widget> children = [];
      for (var message in messageList) {
        var inName = message.inName ?? "";
        var name = message.name ?? "";

        String text = "";
        if (name.isNotEmpty) {
          text = name;
        } else {
          text = inName;
        }

        var type = message.type ?? "";
        if (isText(text, type) && message.val != null && message.val!.isNotEmpty) {
          var content = message.val ?? "";
          var isMarkdown = _isMarkdown(content);
          if (isMarkdown) {
            content = markdown.markdownToHtml(content);
          }
          var view = HtmlWidget(
            content,
            renderMode: RenderMode.column,
            textStyle: const TextStyle(fontSize: 14, color: Colors.white),
          );
          children.add(view);
        }
      }
      return children;
    } else if (data is List<PipeAlbumMessageModel>) {
      final messageList = data;
      List<Widget> children = [];
      for (var message in messageList) {
        var text = message.name ?? "";
        var type = message.type ?? "";
        if (isText(text, type) && message.val.isNotEmpty) {
          var content = message.val ?? "";
          var isMarkdown = _isMarkdown(content);
          if (isMarkdown) {
            content = markdown.markdownToHtml(content);
          }
          var view = HtmlWidget(
            content,
            renderMode: RenderMode.column,
            textStyle: const TextStyle(fontSize: 14, color: Colors.white),
          );
          children.add(view);
        }
      }
      return children;
    }
    return [];
  }

  void _showBottomSheet(BuildContext context) {
    var coverUrl = controller.pipeSceneModel?.pipe.cover ?? "";
    final useNum = Utils.formatNumber(controller.pipeSceneModel?.pipe.useNum ?? 0);
    showModalBottomSheet<void>(
        context: context,
        builder: (BuildContext context) {
          return Container(
            decoration: BoxDecoration(color: const Color(0xFF0E1011), borderRadius: BorderRadius.circular(16)),
            height: 500,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ClipRRect(
                          borderRadius: BorderRadius.circular(5),
                          child: CachedNetworkImage(
                            fit: BoxFit.cover,
                            fadeInDuration: const Duration(milliseconds: 100),
                            fadeOutDuration: const Duration(seconds: 0),
                            imageUrl: coverUrl,
                            width: 70,
                            height: 100,
                          )),
                      const SizedBox(width: 10),
                      Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                        Text(
                          controller.pipeSceneModel?.pipe.name ?? "",
                          style: const TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 15),
                        Text(
                          "@${controller.pipeSceneModel?.pipe.user?.nickname ?? ""} $useNum互动",
                          style: const TextStyle(color: Colors.white60, fontSize: 12),
                        ),
                      ]),
                    ],
                  ),
                  const SizedBox(height: 10),
                  InkWell(
                      onTap: () {
                        Get.back();
                        controller.clearChat();
                      },
                      child: Padding(
                          padding: const EdgeInsets.fromLTRB(0, 4, 0, 0),
                          child: Container(
                            height: 50,
                            decoration: BoxDecoration(
                              color: const Color(0xFF191D22),
                              borderRadius: BorderRadius.circular(10),
                            ),
                            child: const Row(
                              children: [
                                SizedBox(width: 10),
                                Icon(Icons.restart_alt, color: Colors.white, size: 28),
                                SizedBox(width: 10),
                                Text("重置对话", style: TextStyle(fontSize: 16, color: Colors.white)),
                              ],
                            ),
                          ))),
                  const SizedBox(height: 10),
                  const Text("分享给好友", style: TextStyle(fontSize: 16, color: Colors.white24)),
                  const SizedBox(height: 10),
                  InkWell(
                      onTap: () {
                        Fluttertoast.showToast(msg: "QQ分享～");
                      },
                      child: Container(
                        height: 50,
                        decoration: const BoxDecoration(
                          color: Color(0xFF191D22),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(16),
                            topRight: Radius.circular(16),
                            bottomLeft: Radius.circular(4),
                            bottomRight: Radius.circular(4),
                          ),
                        ),
                        child: Row(
                          children: [
                            const SizedBox(width: 10),
                            Image.asset(Images.qq, width: 28, height: 28, fit: BoxFit.cover),
                            const SizedBox(width: 10),
                            const Text("分享给QQ好友", style: TextStyle(fontSize: 16, color: Colors.white)),
                          ],
                        ),
                      )),
                  InkWell(
                      onTap: () {
                        Fluttertoast.showToast(msg: "微信分享～");
                      },
                      child: Padding(
                          padding: const EdgeInsets.fromLTRB(0, 4, 0, 0),
                          child: Container(
                            height: 50,
                            decoration: BoxDecoration(
                              color: const Color(0xFF191D22),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Row(
                              children: [
                                const SizedBox(width: 10),
                                Image.asset(Images.wechat, width: 28, height: 28, fit: BoxFit.cover),
                                const SizedBox(width: 10),
                                const Text("分享给微信好友", style: TextStyle(fontSize: 16, color: Colors.white)),
                              ],
                            ),
                          ))),
                  InkWell(
                    onTap: () {
                      Fluttertoast.showToast(msg: "微信朋友圈分享～");
                    },
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(0, 4, 0, 0),
                      child: Container(
                        height: 50,
                        decoration: BoxDecoration(
                          color: const Color(0xFF191D22),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Row(
                          children: [
                            const SizedBox(width: 10),
                            Image.asset(Images.wechat_timeline, width: 28, height: 28, fit: BoxFit.cover),
                            const SizedBox(width: 10),
                            const Text("分享到朋友圈", style: TextStyle(fontSize: 16, color: Colors.white)),
                          ],
                        ),
                      ),
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Fluttertoast.showToast(msg: "复制链接～");
                    },
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(0, 4, 0, 0),
                      child: Container(
                        height: 50,
                        decoration: const BoxDecoration(
                          color: Color(0xFF191D22),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(4),
                            topRight: Radius.circular(4),
                            bottomLeft: Radius.circular(16),
                            bottomRight: Radius.circular(16),
                          ),
                        ),
                        child: Row(
                          children: [
                            const SizedBox(width: 10),
                            Image.asset(Images.link, width: 28, height: 28, fit: BoxFit.cover),
                            const SizedBox(width: 10),
                            const Text("复制分享链接", style: TextStyle(fontSize: 16, color: Colors.white)),
                          ],
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          );
        });
  }

  _buildTypingIndicator() {
    return Padding(
      padding: EdgeInsets.only(left: 15, bottom: 10),
      child: Container(
        decoration: const BoxDecoration(
          color: Color(0xF22D343E),
          borderRadius: BorderRadius.all(
            Radius.circular(10),
          ),
        ),
        width: 50,
        height: 40,
        child: const Row(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(10),
              child: TypingIndicator2(),
            ),
          ],
        ),
      ),
    );
  }

  _buildConditionalInput(BuildContext context) {
    if (controller.disabledInput.value) {
      if (controller.quickInputSheetButtonList.isEmpty) {
        return const SizedBox.shrink();
      } else {
        return Container(
          color: Colors.black,
          padding: EdgeInsets.only(top: 5, bottom: Get.mediaQuery.padding.bottom),
          child: Column(
            children: _buildQuickInputSheetView(),
          ),
        );
      }
    } else {
      return AnimatedCrossFade(
        sizeCurve: Curves.easeInOut,
        firstChild: _buildInputBar(context),
        secondChild: AudioRecordView(),
        crossFadeState: controller.inputType.value == "audio" ? CrossFadeState.showSecond : CrossFadeState.showFirst,
        duration: Duration(milliseconds: 250),
      );
    }
  }

  _buildMessageText(bool isMe, ChatMessage2 message) {
    var content = message.text;
    bool isMarkdown = message.isMarkdown ?? false;
    if (isMarkdown) {
      content = markdown.markdownToHtml(message.text);
    }
    return HtmlWidget(
      content,
      renderMode: RenderMode.column,
      textStyle: TextStyle(fontSize: 14, color: isMe ? Color(0xFF050805) : Colors.white),
    );
  }

  _buildMediaList(bool isMe, ChatMessage2 message) {
    List<Widget> widgets = message.medias
        .map((media) {
          if (media.type == MediaType2.audio) {
            return AudioMessageView(key: ValueKey(message.medias.first.url), isMe: isMe, audioUrl: message.medias.first.url);
          } else if (media.type == MediaType2.image) {
            double scaledWidth = 200;
            double scaledHeight = 200;
            if (media.customProperties != null) {
              final data = media.customProperties!["data"];
              if (data is PipeAlbumMessageModel) {
                PipeAlbumMessageModel model = data;
                if (model.prop != null) {
                  Map<String, dynamic> imgProp = {};
                  String keyName = "u_prop_${model.name}";
                  if (model.prop!.keys.contains(keyName)) {
                    imgProp = model.prop![keyName];
                  } else {
                    keyName = "u_prop_${model.chainName}";
                    if (model.prop!.keys.contains(keyName)) {
                      imgProp = model.prop![keyName];
                    }
                  }
                  final actualWidth = imgProp["width"] as int;
                  final actualHeight = imgProp["height"] as int;
                  if (actualWidth > actualHeight) {
                    scaledHeight = (actualHeight / actualWidth) * scaledWidth;
                  } else {
                    scaledWidth = (actualWidth / actualHeight) * scaledHeight;
                  }
                }
              } else if (data is MessageItemModel) {}
            }
            return Padding(
              padding: EdgeInsets.only(top: 8),
              child: CachedNetworkImage(
                imageUrl: media.url,
                fit: BoxFit.cover,
                width: scaledWidth,
                height: scaledHeight,
              ),
            );
          }
        })
        .cast<Widget>()
        .toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: widgets,
    );
  }

  Widget _buildButtonItem(String text, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.black54,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: Colors.white30, width: 1),
        ),
        margin: EdgeInsets.only(top: 5, right: 5),
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        child: Text(
          text,
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  _buildMessageBtnList(ChatMessage2 message) {
    final buttonList = message.buttonList;
    var widgets = buttonList.map((data) {
      if (data is PipeAlbumMessageModel) {
        PipeAlbumMessageModel model = data;
        return _buildButtonItem(model.val, () {
          controller.sendPipeAlbum(model.val, model);
        });
      } else if (data is MessageItemModel) {
        MessageItemModel model = data;
        return _buildButtonItem(model.val ?? '', () {
          controller.sendMessageItem(model.val ?? '', model);
        });
      } else {
        return SizedBox.shrink();
      }
    }).toList();

    int layout = 0;
    if (controller.pipeSceneModel?.pipe.wrapper?.btn != null) {
      if (controller.pipeSceneModel?.pipe.wrapper?.btn!["layout"] is int) {
        layout = controller.pipeSceneModel?.pipe.wrapper?.btn!["layout"];
      } else if (controller.pipeSceneModel?.pipe.wrapper?.btn!["layout"] is String) {
        String l = controller.pipeSceneModel?.pipe.wrapper?.btn!["layout"];
        layout = int.tryParse(l) ?? 0;
      }
    }
    return Wrap(direction: layout == 0 ? Axis.horizontal : Axis.vertical, spacing: 4, children: widgets);
  }

  @override
  Widget build(BuildContext context) {
    controller.subscribeToRoute(ModalRoute.of(context) as PageRoute);
    return Obx(
      () => Stack(children: [
        _buildCoverView(),
        Scaffold(
          backgroundColor: Colors.transparent,
          appBar: _buildAppBar(context),
          body: GestureDetector(
            onTap: () {
              FocusScope.of(context).unfocus();
              controller.isPanelVisible.value = false;
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Stack(
                    children: [
                      ListView.builder(
                        physics: BouncingScrollPhysics(),
                        reverse: true,
                        itemCount: controller.messages.length,
                        itemBuilder: (context, index) {
                          final message = controller.messages[index];
                          final isMe = message.isMine;

                          if (message.messageType == MessageType.time) {
                            return Padding(
                              padding: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 8.0),
                              child: Center(
                                child: Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                                  decoration: BoxDecoration(
                                    color: Colors.grey[300],
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: Text(
                                    message.text,
                                    style: TextStyle(color: Colors.black54, fontSize: 14),
                                  ),
                                ),
                              ),
                            );
                          } else if (message.messageType == MessageType.system) {
                            dynamic data = message.customProperties!["data"];
                            return Container(
                              padding: const EdgeInsets.all(10),
                              margin: const EdgeInsets.fromLTRB(30, 10, 30, 0),
                              decoration: BoxDecoration(color: const Color(0xB3000000), borderRadius: BorderRadius.circular(10)),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: _buildSystemMessageWidget(data),
                              ),
                            );
                          } else if (message.messageType == MessageType.narration) {
                            dynamic data = message.customProperties!["data"];
                            return Container(
                              padding: const EdgeInsets.fromLTRB(35, 10, 35, 10),
                              margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                              decoration: BoxDecoration(
                                border: Border.symmetric(
                                  horizontal: BorderSide(color: Colors.white.withAlpha(38), width: 0.5),
                                ),
                                gradient: LinearGradient(
                                  begin: Alignment.centerLeft,
                                  end: Alignment.centerRight,
                                  colors: <Color>[
                                    Colors.transparent,
                                    Colors.black.withAlpha(102),
                                    Colors.black.withAlpha(178),
                                    Colors.black.withAlpha(102),
                                    Colors.transparent,
                                  ],
                                ),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: _buildSystemMessageWidget(data),
                              ),
                            );
                          }

                          return Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
                            child: Column(
                              crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
                              children: [
                                if (!isMe && !isEmpty(message.user.nickname))
                                  Container(
                                    decoration: BoxDecoration(
                                      color: Colors.black38,
                                      borderRadius: BorderRadius.circular(30),
                                    ),
                                    padding: EdgeInsets.symmetric(horizontal: 3, vertical: 2),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        CircleAvatar(
                                          radius: 13,
                                          backgroundImage: NetworkImage(message.user.avatarUrl),
                                        ),
                                        SizedBox(width: 4),
                                        Text(
                                          message.user.nickname,
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: Colors.white,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        SizedBox(width: 4),
                                      ],
                                    ),
                                  ),
                                Container(
                                  margin: isMe ? EdgeInsets.only(left: 80, top: 0, right: 0, bottom: 0) : EdgeInsets.only(left: 0, top: 2, right: 80, bottom: 0),
                                  padding: EdgeInsets.all(12),
                                  decoration: BoxDecoration(
                                    color: isMe ? const Color(0xFF6AE066) : const Color(0xF22D343E),
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      if (!isEmpty(message.text)) _buildMessageText(isMe, message),
                                      if (message.medias.isNotEmpty) _buildMediaList(isMe, message),
                                    ],
                                  ),
                                ),
                                if (message.buttonList.isNotEmpty) _buildMessageBtnList(message),
                              ],
                            ),
                          );
                        },
                      ),
                      Positioned(
                        right: 15,
                        bottom: 15,
                        child: GestureDetector(
                          child: Container(
                            decoration: BoxDecoration(color: Colors.black54, borderRadius: BorderRadius.circular(20), border: Border.all(color: Colors.white24, width: 1)),
                            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            child: Row(
                              children: [
                                Stack(
                                  children: [
                                    Container(
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.only(
                                          topRight: Radius.circular(5),
                                          bottomLeft: Radius.circular(5),
                                          bottomRight: Radius.circular(5),
                                        ),
                                        border: Border.all(color: Colors.white70, width: 1),
                                      ),
                                      width: 16,
                                      height: 13,
                                    ),
                                    Positioned(
                                      left: 2,
                                      bottom: 2,
                                      child: Text(
                                        "...",
                                        style: TextStyle(color: Colors.white70, fontSize: 12),
                                      ),
                                    ),
                                  ],
                                ),
                                if (controller.commentCount.value > 0)
                                  Padding(
                                    padding: EdgeInsets.only(left: 2),
                                    child: Text(
                                      "${controller.commentCount.value}",
                                      style: TextStyle(color: Colors.white70, fontSize: 12),
                                    ),
                                  ),
                              ],
                            ),
                          ),
                          onTap: () {
                            final uid = controller.pipeSceneModel?.pipe.user?.uid ?? '';
                            Get.toNamed(Routes.PIPE_COMMENT, arguments: {"pipeId": Get.arguments["pipeId"], "uid": uid});
                          },
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(height: 5),
                if (controller.isTyping.value) _buildTypingIndicator(),
                SizedBox(height: 5),
                _buildConditionalInput(context),
              ],
            ),
          ),
        )
      ]),
    );
  }
}
